#include <iostream>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <cstring>
#include <chrono>

#define SOCKET_PATH "/tmp/domain_socket"

int main() 
{
    // 创建 socket
    int server_sock = socket(AF_UNIX, SOCK_STREAM, 0);
    if (server_sock == -1) {
        std::cerr << "Socket creation failed" << std::endl;
        return 1;
    }

    // 设置 socket 地址
    struct sockaddr_un addr;
    addr.sun_family = AF_UNIX;
    std::strcpy(addr.sun_path, SOCKET_PATH);

    // 删除之前可能存在的 socket 文件
    unlink(SOCKET_PATH);

    // 绑定 socket 到地址
    if (bind(server_sock, (struct sockaddr*)&addr, sizeof(addr)) == -1) 
    {
        std::cerr << "Bind failed" << std::endl;
        close(server_sock);
        return 1;
    }

    // 监听客户端连接
    if (listen(server_sock, 5) == -1) 
    {
        std::cerr << "Listen failed" << std::endl;
        close(server_sock);
        return 1;
    }

    std::cout << "Server is waiting for a client to connect..." << std::endl;

    // 接受客户端连接
    int client_sock = accept(server_sock, nullptr, nullptr);
    if (client_sock == -1) 
    {
        std::cerr << "Accept failed" << std::endl;
        close(server_sock);
        return 1;
    }

    std::cout << "Client connected, waiting for message..." << std::endl;

    while(true)
    {
        // 接收客户端消息
        char buffer[256];
        ssize_t bytes_received = recv(client_sock, buffer, sizeof(buffer), 0);
        if (bytes_received > 0) 
        {
            buffer[bytes_received] = '\0'; // 确保字符串正确结束

            // 从客户端接收时间戳
            uint64_t client_timestamp;
            std::memcpy(&client_timestamp, buffer, sizeof(client_timestamp));

            // 记录接收的时间戳
            auto server_time = std::chrono::high_resolution_clock::now();
            uint64_t server_timestamp = std::chrono::duration_cast<std::chrono::nanoseconds>(server_time.time_since_epoch()).count();

            std::cout << "Round-trip delay: " << (server_timestamp - client_timestamp)/1000 << " std::chrono::nanoseconds" << std::endl;


            // std::cout << "Received message: " << buffer << std::endl;

            // // 发送响应
            // const char* response = "Hello from server!";
            // send(client_sock, response, std::strlen(response), 0);
        }
    }

    // 关闭 socket
    close(client_sock);
    close(server_sock);
    unlink(SOCKET_PATH); // 删除 socket 文件
    std::cout << "Server shut down" << std::endl;

    return 0;
}
